Vue.component("yl-button", {
  template: `
    <span>
        <el-button :type="type" @click="Export" :loading="loading">
            <slot></slot>
        </el-button>
        <el-table id="ExportData" :data="data" style="display: none; width: 100%;margin-bottom: 20px;">
        <el-table-column align="center" prop="Purchase_Order_SerialNumber" width="300" show-overflow-tooltip label="采购订单编号"></el-table-column>
        <el-table-column align="center" prop="Purchase_Date" width="300" show-overflow-tooltip label="提交时间"></el-table-column>
        <el-table-column align="center" prop="Supplier_SerialNumber" width="150" show-overflow-tooltip label="供应商主键"></el-table-column>
        <el-table-column align="center" prop="Supplier_Name" width="150" show-overflow-tooltip label="供应商"></el-table-column>
        <el-table-column align="center" prop="Amount" width="120" show-overflow-tooltip  label="金额"></el-table-column>
        <el-table-column align="center" prop="Purchase_Amount" width="120" show-overflow-tooltip  label="采购总价"></el-table-column>
        <el-table-column align="center" prop="Paid_Amount" width="120" show-overflow-tooltip label="已付金额"></el-table-column>
        <el-table-column align="center" label="开票状态">
            <template v-slot="{row}">
                <el-tag :type="row.Row_Status.charAt(1)=='0'?'':'success'">{{row.Row_Status.charAt(1)=='0'?'未开票':'已开票'}}</el-tag>
            </template>
        </el-table-column> 
        <el-table-column align="center"  width="100" label="付款状态">
            <template v-slot="{row}">
                <el-tag :type="row.Row_Status.charAt(0)=='0'?'':row.Row_Status.charAt(0)=='1'?'warning':'success'">{{Type(row.Row_Status)}}</el-tag>
            </template>
        </el-table-column> 
        </el-table>
    </span>`,
  props: ["loading", "data", "type"],
  computed: {
    Type() {
      return function (str) {
        switch (str.charAt(0)) {
          case "0":
            return "未付款";
          case "1":
            return "部分付款";
          case "2":
            return "已付款";
          default:
            return "";
        }
      };
    },
  },
  methods: {
    Export() {
      this.$emit("click");
    },
  },
});
Vue.component("yl-detail", {
  template: `
    <span>
        <el-button :type="type" size="small" @click="Export" :loading="loading">
            <slot></slot>
        </el-button>
        <el-table id="ExportDetailData" :data="data" style="display: none; width: 100%;margin-bottom: 20px;">
        <el-table-column align="center" prop="Purchase_Date" label="账单提交时间"></el-table-column>
        <el-table-column align="center" prop="Purchase_Order_SerialNumber"  label="对账单编号"></el-table-column>
        <el-table-column align="center" prop="Sales_Order_SerialNumber" label="订单编号"></el-table-column>
        <el-table-column align="center" prop="Sales_Order_Detail_SerialNumber" label="订单明细编号"></el-table-column>
        <el-table-column align="center" prop="Sales_Date" label="下单时间"></el-table-column>
        <el-table-column align="center" prop="Activity_Name" label="活动名称"></el-table-column>
        <el-table-column align="center" prop="Supplier_Name" label="供应商名称"></el-table-column>
        <el-table-column align="center" prop="Member_Name" label="下单人姓名"></el-table-column>
        <el-table-column align="center" prop="Sales_Contacts" label="收货人姓名"></el-table-column>
        <el-table-column align="center" prop="Sales_Phone" label="收货人联系方式"></el-table-column>
        <el-table-column align="center" prop="Sales_Address" label="收货人联系方式"></el-table-column>
        <el-table-column align="center" prop="Sales_Message" label="订单备注"></el-table-column>
        <el-table-column align="center" prop="Article_Code" label="商品编码"></el-table-column>
        <el-table-column align="center" prop="Article_Name" label="商品名称"></el-table-column>
        <el-table-column align="center" prop="Specifications_Name" label="规格"></el-table-column>
        <el-table-column align="center" prop="Quantity" label="数量"></el-table-column>
        <el-table-column align="center" prop="Purchase_Unit_Price" label="采购单价"></el-table-column>
        <el-table-column align="center" prop="Amount" label="采购总价"></el-table-column>
        </el-table>
    </span>`,
  props: ["loading", "data", "type"],
  computed: {
    Type() {
      return function (str) {
        switch (str.charAt(0)) {
          case "0":
            return "未付款";
          case "1":
            return "部分付款";
          case "2":
            return "已付款";
          default:
            return "";
        }
      };
    },
  },
  methods: {
    Export() {
      this.$emit("click");
    },
  },
});
Vue.component("edit", {
  //修改
  template: `<el-dialog title="付款" :visible.sync="visibleDialog" width="50vw">
        <el-form ref="contract" :model="form" :rules="rules" :inline-message="true">
            <el-descriptions :column="1" border size="small">
                <el-descriptions-item label="付款类型">
                    <el-form-item prop="Payment_Method">
                        <el-select v-model.trim="form.Payment_Method" clearable style="width: 100%;" placeholder="请选择付款类型">
                            <el-option v-for="item in Method" :key="item" :label="item" :value="item"></el-option>
                        </el-select>
                    </el-form-item>
                </el-descriptions-item>
                <el-descriptions-item label="本次付款金额">
                    <el-form-item prop="Amount">
                        <el-input-number v-model="form.Amount" :precision="2" :step="1" :max="max"  :min="0.01"></el-input-number>
                        <span>应付总金额：{{data.Purchase_Amount}}&nbsp;&nbsp;&nbsp;已付金额：{{data.Paid_Amount}}&nbsp;&nbsp;&nbsp;未付金额：{{max}}</span>
                    </el-form-item>
                </el-descriptions-item>
                <el-descriptions-item label="付款凭证">
                    <el-form-item prop="Picture_URL">
                        <yl-upload base64 v-model="form.Picture_URL"></yl-upload>
                    </el-form-item>
                </el-descriptions-item>
            </el-descriptions>
        </el-form> 
        <span slot="footer" class="dialog-footer">
        
            <el-button @click="$emit('update:visible',false)">取消</el-button>
            <el-button type="primary" :loading="loading" @click="submitForm('contract')">确定</el-button>
    
        </span>
    </el-dialog>`,
  props: ["data", "visible"],
  data() {
    return {
      visibleDialog: false,
      form: {
        Business_Order_SerialNumber: "",
        Payment_Method: "",
        Amount: 0,
        Picture_URL: "",
      },
      rules: {
        Payment_Method: [
          { required: true, message: "请选择付款类型", trigger: "change" },
        ],
      },
      Method: ["线下支付"],
      loading: false,
    };
  },
  watch: {
    visible() {
      this.visibleDialog = this.visible;
    },
    visibleDialog(val) {
      this.$emit("update:visible", val);
    },
    data: {
      handler(newVal) {
        this.form.Amount = accSub(
          this.data.Purchase_Amount,
          this.data.Paid_Amount
        );
      },
      deep: true,
    },
  },
  computed: {
    max() {
      return parseFloat(
        accSub(this.data.Purchase_Amount, this.data.Paid_Amount)
      );
    },
  },
  methods: {
    submitForm(formName) {
      const that = this;
      this.$refs[formName].validate((valid) => {
        if (valid) {
          //1.修改采购订单
          that.loading = true;
          let item = deepClone(that.data);
          if (
            parseFloat(accAdd(item.Paid_Amount, that.form.Amount)) ==
            parseFloat(item.Purchase_Amount)
          ) {
            //全额付款
            item.Paid_Amount = accAdd(item.Paid_Amount, that.form.Amount);
            item.Row_Status = "2" + item.Row_Status.charAt(1);
          } else {
            //部分付款
            item.Paid_Amount = accAdd(item.Paid_Amount, that.form.Amount);
            item.Row_Status = "1" + item.Row_Status.charAt(1);
          }
          //2.生成付款表，付款明细
          let obj = {
            Payment_SerialNumber: "",
            Supplier_SerialNumber: that.data.Supplier_SerialNumber,
            Payment_Date: getYMDHMSDate(),
            Payment_Amount: that.form.Amount,
            Amount: that.form.Amount,
            Bank_Voucher_SerialNumber: "",
            Row_Status: 1,
            Children: {
              business_payment_detail: [
                {
                  Payment_Detail_SerialNumber: "",
                  Payment_SerialNumber: "",
                  Business_Order_SerialNumber:
                    that.data.Purchase_Order_SerialNumber,
                  Payment_Method: that.form.Payment_Method,
                  Payment_Type: "0",
                  Amount: that.form.Amount,
                },
              ],
            },
          };
          if (that.form.Picture_URL) {
            obj.Children.business_payment_voucher = [
              {
                Payment_Voucher_SerialNumber: "",
                Payment_SerialNumber: "",
                Payment_Voucher_Picture: that.form.Picture_URL,
              },
            ];
          }
          console.log(obj);

          $.ajax({
            headers: requestHeaders(),
            url: `${BASE_URL2}/generalBusiness/generalSave`,
            type: "POST",
            data: {
              Data: JSON.stringify({
                Add: {
                  business_payment: [obj],
                  base_operation_log: [
                    generateLog(
                      "付款" + that.form.Amount + "元",
                      "平台端操作",
                      "business_purchase_order",
                      JSON.stringify({
                        Modify: { business_purchase_order: [item] },
                        Add: { business_payment: [obj] },
                      })
                    ),
                  ],
                },
                Modify: { business_purchase_order: [item] },
              }),
            },
            success: function (res) {
              if (res.Status === "success") {
                that.$message.success("提交成功");
                that.$emit("update:visible", false);
                that.$emit("success");
                that.form = {
                  Business_Order_SerialNumber: "",
                  Payment_Method: "",
                  Amount: 0,
                  Picture_URL: "",
                };
              } else {
                that.$message.error("提交失败，请稍后再试");
              }
            },
            complete: function (XMLHttpRequest) {
              that.loading = false;
              requestPretreatment(XMLHttpRequest);
            },
            dataType: "json",
          });
        }
      });
    },
  },
});
Vue.component("show-detail", {
  template: `<el-dialog title="详情查看" :visible.sync="visibleDialog" width="80vw">
    <el-tabs v-model="activeName">
        <el-tab-pane label="订单明细" name="1">
            <el-table :data="tableData" stripe border height="40vh" style="width: 100%">
                <el-table-column align="center" type="index" label="序号" width="50"></el-table-column>
                <el-table-column align="center" width="200" show-overflow-tooltip prop="Sales_Order_Detail_SerialNumber" label="销售订单明细"></el-table-column>
                <el-table-column align="center" width="200" show-overflow-tooltip prop="Purchase_Order_SerialNumber" label="采购订单"></el-table-column>
                <el-table-column align="center" width="120" show-overflow-tooltip prop="Supplier_Name" label="供应商"></el-table-column>
                <el-table-column align="center" width="120" show-overflow-tooltip prop="Article_Name" label="商品名称"></el-table-column>
                <el-table-column align="center" width="120" show-overflow-tooltip prop="Specifications_Name" label="规格名称"></el-table-column>
                <el-table-column align="center" width="120" show-overflow-tooltip prop="Member_Name" label="下单账户"></el-table-column>
                <el-table-column align="center" width="120" show-overflow-tooltip prop="Sales_Contacts" label="收件人"></el-table-column>
                <el-table-column align="center" width="120" show-overflow-tooltip prop="Sales_Phone" label="手机号"></el-table-column>
                <el-table-column align="center" min-width="220" show-overflow-tooltip prop="Sales_Address" label="收货地址"></el-table-column>
                <el-table-column align="center" width="170" show-overflow-tooltip prop="Sales_Date" label="下单时间"></el-table-column>
                <el-table-column align="center" width="100" show-overflow-tooltip prop="Notes" label="备注"></el-table-column>
                <el-table-column align="center" width="130" show-overflow-tooltip prop="Purchase_Amount" label="实际对账金额"></el-table-column>
                <el-table-column align="center" width="100" fixed="right" show-overflow-tooltip prop="Purchase_Unit_Price" label="采购单价"></el-table-column>
                <el-table-column align="center" width="100" fixed="right" show-overflow-tooltip prop="Quantity" label="采购数量"></el-table-column>
                <el-table-column align="center" width="100" fixed="right" show-overflow-tooltip prop="Amount" label="采购总价"></el-table-column>
                
                <el-table-column align="center" prop="Row_Status" fixed="right" label="订单状态">
                    <template v-slot="{row}">
                        <el-tag :type="Type(row.Row_Status)[1]">
                            {{Type(row.Row_Status)[0]}}
                        </el-tag>
                    </template>  
                </el-table-column>
            </el-table>
            <el-pagination style="margin-top: 5px;" background @size-change="handleSizeChange"
                @current-change="handleCurrentChange" :current-page="form.page" :page-sizes="[20, 30, 50 ,100]"
                :page-size="form.limit" layout="total, sizes, prev, pager, next, jumper" :total="total">
            </el-pagination>
        </el-tab-pane>
        <el-tab-pane label="付款详情" name="2">
            <el-table :data="tableData1" stripe border max-height="40vh" style="width: 100%">
                <el-table-column align="center" type="index" label="序号" width="50"></el-table-column>
                <el-table-column align="center" prop="Payment_SerialNumber" label="付款单号"></el-table-column>
                <el-table-column align="center" width="180" show-overflow-tooltip prop="Payment_Date" label="付款时间"></el-table-column>
                <el-table-column align="center" prop="Supplier_Name" label="供应商"></el-table-column>
                <el-table-column align="center" show-overflow-tooltip prop="Payment_Method" label="付款方式"></el-table-column>
                <el-table-column align="center" show-overflow-tooltip prop="Amount" label="付款金额"></el-table-column>
                <el-table-column align="center" show-overflow-tooltip prop="Payment_Voucher_Picture" label="付款凭证">
                    <template v-slot="{row}">
                        <el-image :preview-src-list="[row.Payment_Voucher_Picture]" v-if="row.Payment_Voucher_Picture" fit="contain" :src="row.Payment_Voucher_Picture" style="width:100px;height: 100px;"></el-image>
                        <span v-else>未上传凭证</span>
                    </template>  
                </el-table-column>
                <el-table-column align="center" show-overflow-tooltip prop="Row_Status" label="付款状态">
                    <template v-slot="{row}">
                        {{row.Row_Status!='0'?'已付款':'未付款'}}
                    </template>  
                </el-table-column>
                <el-table-column align="center" prop="Row_Status" label="对方是否确认">
                    <template v-slot="{row}">
                        {{row.Row_Status=='2'?'已确认':'未确认'}}
                    </template>  
                </el-table-column>
            </el-table>
        </el-tab-pane>
        <el-tab-pane label="发票预览" name="3">
            <el-table :data="Data" stripe border height="40vh" style="width: 100%" @expand-change="expandChange">
                <el-table-column align="center" type="expand" width="50">
                    <template slot-scope="{row}">
                        <el-table :data="row.Children.detail" stripe border style="width: 100%" > 
                            <el-table-column align="center" type="index" label="序号" width="50"></el-table-column>
                            <el-table-column align="center" prop="Purchase_Order_Detail_SerialNumber" show-overflow-tooltip label="采购订单明细"></el-table-column>
                            <el-table-column align="center" prop="Article_Name" show-overflow-tooltip label="商品名称"></el-table-column>
                            <el-table-column align="center" prop="Specifications_Name" show-overflow-tooltip label="规格名称"></el-table-column>
                            <el-table-column align="center" prop="Purchase_Unit_Price" show-overflow-tooltip label="采购单价"></el-table-column>
                            <el-table-column align="center" prop="Quantity" show-overflow-tooltip label="数量"></el-table-column>
                            <el-table-column align="center" prop="Amount" show-overflow-tooltip label="总价"></el-table-column>
                        </el-table>
                    </template>
                </el-table-column>
                <el-table-column align="center" type="index" label="序号" width="50"></el-table-column>
                <el-table-column align="center" prop="Purchase_Order_Invoice_SerialNumber" label="上传流水号"></el-table-column>
                <el-table-column align="center" prop="Payment_SerialNumber" label="发票">
                    <template v-slot="{row}">
                        <div style="display: flex; align-items:center;flex-direction: column;">
                            <el-image :preview-src-list="row.Pic" fit="contain" :src="row.Invoice_Picture" style="width:100px;height: 100px;"></el-image>
                            <span style="font-size: 12px;">点击图片查看剩余发票</span>
                        </div>
                    </template>  
                </el-table-column>
                <el-table-column align="center" prop="Submit_Date" label="上传时间"></el-table-column>
            </el-table>
        </el-tab-pane>
    </el-tabs>
        <span slot="footer" class="dialog-footer">
            <el-button @click="$emit('update:visible',false)">取消</el-button>
            <el-button type="primary" @click="$emit('update:visible',false)">确定</el-button>
        </span>
    </el-dialog>`,
  props: ["data", "visible"],
  data() {
    return {
      visibleDialog: false,
      tableData: [], //详情
      tableData1: [], //详情
      tableData2: [],
      form: {
        SQLSerialNumber: "P_business_purchase_order_detail",
        PaginationNumber: 1, //页数
        RowAmount: 10, //每页数据条数
        Condition: "",
        ExtensionCondition: "",
      },
      form1: {
        SQLSerialNumber: "P_business_payment_detail",
        Condition: "",
        ExtensionCondition: "",
      },
      total: 0,
      activeName: "1",
      loading: false,
      isSupplier: false,
    };
  },
  computed: {
    Type() {
      return function (str) {
        switch (str.charAt(1)) {
          case "0":
            return ["待付款", ""];
          case "1":
            return ["待付款", ""];
          case "2":
            return ["待付款", ""];
          case "3":
            return ["已付款", "success"];
          case "4":
            return ["已发货", "warning"];
          case "5":
            return ["已完成", "info"];
          case "6":
            return ["已取消", "danger"];
          case "7":
            return ["已取消", "danger"];
          default:
            return "";
        }
      };
    },
    Data() {
      let arr = [];
      this.tableData2.forEach((item) => {
        let arr1 = arr.filter(
          (i) =>
            i.Purchase_Order_Invoice_SerialNumber ==
            item.Purchase_Order_Invoice_SerialNumber
        )[0];
        if (arr1) {
          arr1.Pic.push(item.Invoice_Picture);
        } else {
          arr.push({
            ...item,
            Pic: [item.Invoice_Picture],
          });
        }
      });
      return arr;
    },
  },
  mounted() {
    if (getCookie("role")) {
      this.activeName = "2";
      this.isSupplier = true;
    }
  },
  watch: {
    visible() {
      this.visibleDialog = this.visible;
    },
    visibleDialog(val) {
      this.$emit("update:visible", val);
      if (val) {
        this.tableData = [];
        (this.tableData1 = []), //详情
          (this.tableData2 = []),
          (this.form.Condition = window.btoa(
            unescape(encodeURIComponent(this.data.Purchase_Order_SerialNumber))
          ));
        this.form1.Condition = window.btoa(
          unescape(encodeURIComponent(this.data.Purchase_Order_SerialNumber))
        );
        this.getList(this.form);
        this.getList1(this.form1);
        this.getList2(this.data.Purchase_Order_SerialNumber);
      }
    },
  },
  methods: {
    handleSizeChange(val) {
      this.form.PaginationNumber = 1;
      this.form.RowAmount = val;
      this.getList(this.form);
    },
    handleCurrentChange(val) {
      this.form.PaginationNumber = val;
      this.getList(this.form);
    },
    getList(data) {
      const that = this;
      $.ajax({
        headers: requestHeaders(),
        url: `${BASE_URL2}/generalBusiness/generalPaginationQueryBySQLSerialNumber`,
        type: "POST",
        data,
        success: function (Result) {
          that.tableData = Result.Rows;
          that.total = Result.TotalRows;
        },
        complete: function (XMLHttpRequest) {
          requestPretreatment(XMLHttpRequest);
        },
        dataType: "json",
      });
    },
    getList1(data) {
      const that = this;
      $.ajax({
        headers: requestHeaders(),
        url: `${BASE_URL2}/generalBusiness/generalQueryBySQLSerialNumber`,
        type: "POST",
        data,
        success: function (Result) {
          that.tableData1 = Result;
        },
        complete: function (XMLHttpRequest) {
          requestPretreatment(XMLHttpRequest);
        },
        dataType: "json",
      });
    },
    expandChange(row) {
      //展开
      console.log(row.Purchase_Order_Invoice_SerialNumber);
      $.ajax({
        headers: requestHeaders(),
        url: `${BASE_URL2}/generalBusiness/generalQueryBySQLSerialNumber`,
        type: "POST",
        data: {
          SQLSerialNumber: "A_business_purchase_order_invoice_log",
          Condition: window.btoa(
            unescape(
              encodeURIComponent(row.Purchase_Order_Invoice_SerialNumber)
            )
          ),
          ExtensionCondition: "",
        },
        success: function (Result) {
          row.Children.detail = Result;
        },
        complete: function (XMLHttpRequest) {
          requestPretreatment(XMLHttpRequest);
        },
        dataType: "json",
      });
    },
    getList2(Purchase_Order_SerialNumber) {
      const that = this;
      $.ajax({
        headers: requestHeaders(),
        url: `${BASE_URL2}/generalBusiness/generalQueryBySQLSerialNumber`,
        type: "POST",
        data: {
          SQLSerialNumber: "A_business_purchase_order_invoice",
          Condition: window.btoa(
            unescape(encodeURIComponent(Purchase_Order_SerialNumber))
          ),
          ExtensionCondition: "",
        },
        success: function (Result) {
          Result.forEach((item) => {
            item.Children = {
              detail: [],
            };
          });
          that.tableData2 = Result;
        },
        complete: function (XMLHttpRequest) {
          requestPretreatment(XMLHttpRequest);
        },
        dataType: "json",
      });
    },
  },
});
Vue.component("invoice", {
  template: `<el-dialog title="上传发票" :visible.sync="visibleDialog" >
        <el-table v-if="tab=='1'" :data="tableData" stripe border height="55vh"  @selection-change="handleSelectionChange">
            <el-table-column align="center" type="selection" :selectable="selectable" width="50"></el-table-column>    
            <el-table-column align="center" type="index" label="序号" width="50"></el-table-column>
            <el-table-column align="center" prop="Article_Name" show-overflow-tooltip label="商品名称" width="280"></el-table-column>
            <el-table-column align="center" prop="Sales_Unit_Price" show-overflow-tooltip label="单价"></el-table-column>
            <el-table-column align="center" prop="Quantity" show-overflow-tooltip label="数量"></el-table-column>
            <el-table-column align="center" prop="Amount" show-overflow-tooltip label="总价"></el-table-column>
            <el-table-column align="center" prop="Row_Status" show-overflow-tooltip label="是否开票">
                <template v-slot="{row}">
                    {{row.Row_Status=='0'?'未开票':'已开票'}}
                </template>
            </el-table-column>
        </el-table>
        <div v-if="tab=='2'">
            <el-upload class="upload-demo" style="flex-shrink: 0;" :show-file-list="false" accept="image/*" drag :on-change="upload" :auto-upload="false" action="" multiple>
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将发票拖到此处，或<em>点击上传</em></div>
                <div class="el-upload__tip" slot="tip">
                    只能上传jpg/png文件，且不超过500kb
                    <el-slider :min="1" v-model="quality" :format-tooltip="formatTooltip"></el-slider>
                    <div v-show="quality < 100">当前图片压缩至{{quality}}%</div>
                </div>
            </el-upload>
            <div style="width:100%; margin-left: 20px; overflow-y: auto;">
                <div class="preview" v-for="(item,index) in form" :key="item">
                    <el-image :ref="'Invoice'+index" :preview-src-list="[item.Invoice_Picture]"
                        class="el-upload-list__item-thumbnail" fit="contain" :src="item.Invoice_Picture"
                            style="width: 148px; height: 148px;"></el-image>
                    <span class="el-upload-list__item-actions">
                        <span @click="handleImgClick('Invoice'+index)" style="cursor: pointer;"><i
                            class="el-icon-zoom-in"></i></span>
                        <span @click="RemoveImage(index)" style="cursor: pointer;"><i
                            class="el-icon-delete"></i></span>
                    </span>
                </div>
                
            </div>
            
            <el-form ref="form" :model="form1" label-width="80px">
                <el-form-item label="发票号">
                <el-input v-model="form1.name"></el-input>
             </el-form>   
        </div>
        
        <span slot="footer" class="dialog-footer">
      
            <el-button :type="tab=='1'?'primary':''" @click="activeTab">{{tab=='1'?'上传发票':'返回'}}</el-button>
            <el-button v-if="tab=='2'" type="primary" @click="submitForm">确定</el-button>
        </span>
    </el-dialog>`,
  props: ["data", "visible"],
  data() {
    return {
      form1: {name:''},
      input: "",
      visibleDialog: false,
      quality: 100,
      form: [],
      tableData: [],
      loading: false,
      tab: 1,
      multipleSelection: [],
    };
  },
  watch: {
    visible() {
      this.visibleDialog = this.visible;
    },
    visibleDialog(val) {
      this.$emit("update:visible", val);
      this.form = [];
      this.tab = "1";
      if (val) {
        this.getList(this.data.Purchase_Order_SerialNumber);
      }
    },
  },
  methods: {
    getList(Purchase_Order_SerialNumber) {
      const that = this;
      $.ajax({
        headers: requestHeaders(),
        url: `${BASE_URL2}/generalBusiness/generalQueryBySQLSerialNumberWithOriginal`,
        type: "POST",
        data: {
          SQLSerialNumber: "A_business_purchase_order_detail",
          Condition: window.btoa(
            unescape(encodeURIComponent(Purchase_Order_SerialNumber))
          ),
          ExtensionCondition: "",
        },
        success: function (Result) {
          console.log(Result);
          that.tableData = Result;
        },
        complete: function (XMLHttpRequest) {
          requestPretreatment(XMLHttpRequest);
        },
        dataType: "json",
      });
    },
    activeTab() {
      //开票主体
      if (this.tab == 1) {
        if (this.multipleSelection.length > 0) {
          this.tab = 2;
        } else {
          this.$message({
            type: "warning",
            message: "请选择明细",
          });
        }
      } else {
        this.tab = 1;
      }
    },
    selectable(row) {
      return row.Row_Status == "0";
    },
    formatTooltip(val) {
      return "图片压缩比例：" + val + "%";
    },
    upload({ raw }) {
      const that = this;
      new Compressor(raw, {
        quality: that.quality / 100,
        success(file) {
          const isJPGorPNG =
            file.type === "image/jpeg" || file.type === "image/png";
          const isLt500K = file.size / 1024 / 1024 < 0.5; // 500KB
          if (!isJPGorPNG) {
            that.$message({
              message: "上传头像图片只能是 JPG/PNG 格式!",
              type: "warning",
            });
            return false;
          }
          if (!isLt500K) {
            that.$message({
              message: "上传图片大小不能超过 500KB! 可压缩后上传",
              type: "warning",
            });
            return false;
          }
          const formData = new FormData();
          formData.append("file", file, file.name);
          let oFileReader = new FileReader();
          oFileReader.readAsDataURL(file);
          oFileReader.onload = function (e) {
            that.form.push({
              Invoice_SerialNumber: "",
              Purchase_Order_Invoice_SerialNumber: "",
              Invoice_Picture: e.target.result,
            });
          };
        },
      });
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handleImgClick(formName) {
      //点击查看图片
      this.$refs[formName][0].showViewer = true;
    },
    RemoveImage(index) {
      //删除图片
      this.form.splice(index, 1);
    },
    submitForm() {
      const that = this;
      if (that.form.length > 0) {
        that.loading = true;
        let business_purchase_order_invoice_log = [];
        this.multipleSelection.forEach((item) => {
          business_purchase_order_invoice_log.push({
            Log_SerialNumber: "",
            Purchase_Order_Invoice_SerialNumber: "",
            Purchase_Order_Detail_SerialNumber:
              item.Purchase_Order_Detail_SerialNumber,
          });
          item.Row_Status = "1";
        });
        let obj = {
          Purchase_Order_Invoice_SerialNumber: "",
          Purchase_Order_SerialNumber: this.data.Purchase_Order_SerialNumber,
          Invoice_Picture: "",
          Invoice_SerialNumber:this.form1.name,
          Submit_Date: getYMDHMSDate(),
          Children: {
            business_purchase_order_invoice_detatil: this.form,
            business_purchase_order_invoice_log,
          },
        };

        let item = deepClone(that.data);
        item.Row_Status = item.Row_Status = item.Row_Status.charAt(0) + "1";
        $.ajax({
          headers: requestHeaders(),
          url: `${BASE_URL2}/generalBusiness/generalSave`,
          type: "POST",
          data: {
            Data: JSON.stringify({
              Add: {
                business_purchase_order_invoice: [obj],
                base_operation_log: [
                  generateLog(
                    "上传发票",
                    "平台端操作",
                    "business_purchase_order",
                    JSON.stringify({
                      Modify: {
                        business_purchase_order: [item],
                        business_purchase_order_detail: this.multipleSelection,
                      },
                      Add: { business_purchase_order_invoice: [obj] },
                    })
                  ),
                ],
              },
              Modify: {
                business_purchase_order: [item],
                business_purchase_order_detail: this.multipleSelection,
              },
            }),
          },
          success: function (res) {
            if (res.Status === "success") {
              that.$message.success("提交成功");
              that.tab = "1";
              that.$emit("update:visible", false);
              that.$emit("success");
            } else {
              that.$message.error("未知错误");
            }
          },
          complete: function (XMLHttpRequest) {
            that.loading = false;
            requestPretreatment(XMLHttpRequest);
          },
          dataType: "json",
        });
      } else {
        that.$message({
          message: "当前没有需要上传的发票",
          type: "warning",
        });
      }
    },
  },
});
new Vue({
  el: "#app",
  data() {
    return {
      form: {
        SQLSerialNumber: "P_business_purchase_order",
        PaginationNumber: 1, //页数
        RowAmount: 20, //每页数据条数
        Condition: "",
        ExtensionCondition: "",
        Supplier_SerialNumber: "",
        Purchase_Order_SerialNumber: "",
        Purchase_Date: null,
        Row_Status: "-",
        page:1,
        limit:10,
      },
      Supplier: [],
      total: 0,
      tableData: [], //表格数据
      ExportData: [], //导出
      ExportDetailData: [], //
      loading: false,
      dialogVisible: false, //详情
      dialogEditVisible: false, //付款
      dialogInvoiceVisible: false, //发票
      Purchase_Order: {}, //当前选中的订单
      isSupplier: false,
    };
  },
  mounted() {
    if (getCookie("role")) {
      this.isSupplier = true;
      let roleObj = JSON.parse(getCookie("role"));
      this.Supplier_SerialNumber = roleObj.other;
    }
    this.getData();
    this.getList(this.form); //前端分页
  },
  computed: {
    Type() {
      return function (str) {
        switch (str.charAt(0)) {
          case "0":
            return "未付款";
          case "1":
            return "部分付款";
          case "2":
            return "已付款";
          default:
            return "";
        }
      };
    },
  },
  methods: {
    formatRatio(receiptQuantity, purchaseAmount) {
      if (purchaseAmount === 0) return "N/A"; // 避免除以零错误
      return ((receiptQuantity - purchaseAmount) / purchaseAmount).toFixed(2);
    },
    resetDateFilter() {
      this.$refs.filterTable.clearFilter("date");
    },
    clearFilter() {
      this.$refs.filterTable.clearFilter();
    },
    formatter(row, column) {
      return row.address;
    },
    filterTag(value, row) {
      return row.Row_Status.charAt(1) === value;
    },
    filterTag1(value, row) {
      return row.Row_Status === value;
    },
    onSerach() {
      //查询方法
      this.form.PaginationNumber = 1;
      this.getList(this.form);
    },
    handleSizeChange(val) {
      this.page = 1;
      this.form.limit = val;
      // this.form.PaginationNumber = 1;
      // this.form.RowAmount = val;
      // this.getList(this.form);
    },
    handleCurrentChange(val) {
      this.form.page = val
      // this.form.PaginationNumber = val;
      // this.getList(this.form);
    },
    handle(command, row) {
      const that = this;
      $.ajax({
        headers: requestHeaders(),
        url: `${BASE_URL2}/generalBusiness/generalQueryByTableNameWithOriginal`,
        type: "POST",
        data: {
          Data: "business_purchase_order",
          Condition:
            "Purchase_Order_SerialNumber = '" +
            row.Purchase_Order_SerialNumber +
            "'",
        },
        success: function (business_purchase_order) {
          if (command == "true") {
            business_purchase_order[0].Row_Status = "00";
          } else if (command == "false") {
            business_purchase_order[0].Row_Status = "88";
          }
          $.ajax({
            headers: requestHeaders(),
            url: `${BASE_URL2}/generalBusiness/generalSave`,
            type: "POST",
            data: {
              Data: JSON.stringify({
                Modify: { business_purchase_order },
              }),
            },
            success: function (res) {
              if (res.Status === "success") {
                that.$message({
                  type: "success",
                  message: "操作成功!",
                });
                that.getData();
              } else {
                that.$message.error("操作失败，请稍后再试");
              }
            },
            error: function () {
              that.$message.error("删除失败，请稍后再试");
            },
            complete: function (XMLHttpRequest) {
              that.loading = false;
              requestPretreatment(XMLHttpRequest);
            },
            dataType: "json",
          });
        },
        error: function () {
          that.$message.error("操作失败，请稍后再试");
        },
        complete: function (XMLHttpRequest) {
          that.loading = false;
          requestPretreatment(XMLHttpRequest);
        },
        dataType: "json",
      });
    },
    getData() {
      const that = this;
      $.ajax({
        headers: requestHeaders(),
        url: `${BASE_URL2}/generalBusiness/generalQueryByTableName`,
        type: "POST",
        data: {
          Data: "business_supplier_info",
          Condition: "Row_Status <> '1'",
        },
        success: function (res) {
          that.Supplier = res;
        },
        error: function () {
          that.$message.error("操作失败，请稍后再试");
        },
        complete: function (XMLHttpRequest) {
          that.loading = false;
          requestPretreatment(XMLHttpRequest);
        },
        dataType: "json",
      });
    },
    ExportDetail(row) {
      const that = this;
      let data = {
        SQLSerialNumber: "P_business_purchase_order_detail",
        Condition: window.btoa(
          unescape(encodeURIComponent(row.Purchase_Order_SerialNumber))
        ),
        ExtensionCondition: "",
      };
      $.ajax({
        headers: requestHeaders(),
        url: `${BASE_URL2}/generalBusiness/generalQueryBySQLSerialNumber`,
        type: "POST",
        data,
        success: function (Result) {
          if (Result.length > 0) {
            let ExportData = Result;
            const wb = XLSX.utils.book_new();
            const ws_data = [
              [
                "账单提交时间",
                "对账单编号",
                "订单编号",
                "订单明细编号",
                "下单时间",
                "活动名称",
                "供应商名称",
                "下单人姓名",
                "收货人姓名",
                "收货人联系方式",
                "收货人地址",
                "订单备注",
                "商品编码",
                "商品名称",
                "规格",
                "数量",
                "采购单价",
                "采购总价",
                "平台单价",
                "平台总价",
                "利润",
                "利润率",
              ],
            ];
            ExportData.forEach((item) => {
              ws_data.push([
                item.Purchase_Date,
                item.Purchase_Order_SerialNumber,
                item.Sales_Order_SerialNumber,
                item.Sales_Order_Detail_SerialNumber,
                item.Sales_Date,
                item.Activity_Name,
                item.Supplier_Name,
                item.Activity_Name,
                item.Member_Name,
                item.Sales_Contacts,
                item.Sales_Phone,
                item.Sales_Address,
                item.Article_Code,
                item.Article_Name,
                item.Specifications_Name,
                item.Quantity,
                item.Purchase_Unit_Price,
                item.Amount,
                item.Sales_Unit_Price,
                item.Sales_Amount,
                accSub(item.Sales_Amount, item.Amount),
                (
                  accDiv(
                    accSub(item.Sales_Amount, item.Amount),
                    item.Sales_Amount
                  ) * 100
                ).toFixed(2),
              ]);
            });
            const ws = XLSX.utils.aoa_to_sheet(ws_data);
            ws["!cols"] = [];
            ws_data[0].forEach((item) => {
              ws["!cols"].push({
                alignment: { horizontal: "center" },
                wpx: 150,
              });
            });
            XLSX.utils.book_append_sheet(wb, ws, "对账明细");
            XLSX.writeFile(wb, "对账明细信息表" + +new Date() + ".xlsx");
            that.$emit('success');
            that.$message({
              message: "已成功导出",
              type: "success",
            });
            // that.ExportDetailData = Result;
            // console.log(Result);
            // that.$nextTick(() => {
            //     let wb = XLSX.utils.table_to_book(document.querySelector("#ExportDetailData"));
            //     var wbout = XLSX.write(wb, {
            //         bookType: "xlsx",
            //         bookSST: true,
            //         type: "array"
            //     });
            //     try {
            //         saveAs(
            //             new Blob([wbout], {
            //                 type: "application/octet-stream"
            //             }),
            //             "采购订单明细表" + (+new Date()) + ".xlsx"
            //         );
            //     } catch (e) {
            //         if (typeof console !== "undefined") console.log(e, wbout);
            //     }
            //     that.$message({
            //         message: '已成功导出',
            //         type: 'success'
            //     })
            //     return wbout;
            // })
          }
        },
        complete: function (XMLHttpRequest) {
          that.loading = false;
          requestPretreatment(XMLHttpRequest);
        },
        dataType: "json",
      });
    },
    getList() {
      //换页方法
      console.log(this.form);
      // this.form.start = this.form.Purchase_Date[0];
      // this.form.end = this.form.Purchase_Date[1];
      // this.form.offset = this.form.PaginationNumber;
      // this.form.pageSize = this.form.RowAmount;
      // this.form.Reconciliation_Name = this.form.Purchase_Order_SerialNumber;

      const _this = this;
      //500
      $.ajax({
        // headers: requestHeaders(),
        // url: `${BASE_URL2}/generalBusiness/generalPaginationQueryBySQLSerialNumber`,
        // url: "https://service.kdddy.cn/hnx/get/getPurchase",
        url: "https://service.kdddy.cn/hnx/get/getPurchase",

        type: "get",
        // data: JSON.stringify([
        //   {
        //     start: "", //表名
        //     end: "",
        //     Reconciliation_Name: "",
        //     Reconciliation_People: "",
        //     Clerk: "",
        //     pageSize: 100,
        //     offset: 1,
        //   },
        // ]),

        data: {
          pageSize: 100,
          pageNumber: 1,
        },
        success: function (Result) {
          console.log(Result);
          _this.tableData = Result.Data;
          //   if (Result.Status === "success") {
          //     _this.$message.success("提交成功");
          //     window.history.go(-1);
          //   } else {
          //     _this.$message.error("提交失败，请稍后再试");
          //   }
        },
        complete: function (XMLHttpRequest) {
          requestPretreatment(XMLHttpRequest); //config/config.js 响应预检
        },
        dataType: "json",
      });
      //   let data = deepClone(form);
      //   data.Condition = window.btoa(
      //     unescape(
      //       encodeURIComponent("%" + data.Purchase_Order_SerialNumber + "%")
      //     )
      //   );
      //   let sql = "";
      //   if (data.Purchase_Date) {
      //     sql =
      //       sql +
      //       "AND business_purchase_order.Purchase_Date BETWEEN '" +
      //       data.Purchase_Date[0] +
      //       "' AND '" +
      //       data.Purchase_Date[1] +
      //       "'\r\n";
      //   }
      //   if (data.Supplier_SerialNumber) {
      //     sql =
      //       sql +
      //       "AND business_purchase_order.Supplier_SerialNumber = '" +
      //       data.Supplier_SerialNumber +
      //       "'\r\n";
      //   }
      //   if (data.Row_Status != "-") {
      //     if (data.Row_Status == "0") {
      //       sql = sql + " AND business_purchase_order.Row_Status = '99'\r\n";
      //     } else if (data.Row_Status == "1") {
      //       sql =
      //         sql +
      //         " AND (business_purchase_order.Row_Status <> '99' OR business_purchase_order.Row_Status <> '88')\r\n";
      //     } else if (data.Row_Status == "2") {
      //       sql = sql + " AND business_purchase_order.Row_Status = '88'\r\n";
      //     }
      //   }
      //   data.ExtensionCondition = window.btoa(unescape(encodeURIComponent(sql)));
      //   $.ajax({
      //     headers: requestHeaders(),
      //     url: `${BASE_URL2}/generalBusiness/generalPaginationQueryBySQLSerialNumber`,
      //     type: "POST",
      //     data,
      //     success: function (Result) {
      //       that.tableData = Result.Rows;
      //       that.total = Result.TotalRows;
      //     },
      //     complete: function (XMLHttpRequest) {
      //       requestPretreatment(XMLHttpRequest);
      //     },
      //     dataType: "json",
      //   });
    },
    Add() {
      window.location.href = "./add.html";
    },
    Show(row) {
      console.log(row);

      //查看详情
      this.Purchase_Order = row;
      this.dialogVisible = true;
    },
    Edit(row) {
      console.log(row);

      this.Purchase_Order = row;
      this.dialogEditVisible = true;
    },
    Invoice(row) {
      this.Purchase_Order = row;
      this.dialogInvoiceVisible = true;
    },
    Export(form) {
      //导出
      const that = this;
      this.loading = true;
      let data = deepClone(form);
      data.Condition = window.btoa(
        unescape(
          encodeURIComponent("%" + data.Purchase_Order_SerialNumber + "%")
        )
      );
      let sql = "";
      if (data.Purchase_Date) {
        sql =
          sql +
          "AND business_purchase_order.Purchase_Date BETWEEN '" +
          data.Purchase_Date[0] +
          "' AND '" +
          data.Purchase_Date[1] +
          "'\r\n";
      }
      if (data.Supplier_SerialNumber) {
        sql =
          sql +
          "AND business_purchase_order.Supplier_SerialNumber = '" +
          data.Supplier_SerialNumber +
          "'\r\n";
      }
      data.ExtensionCondition = window.btoa(unescape(encodeURIComponent(sql)));
      $.ajax({
        headers: requestHeaders(),
        url: `${BASE_URL2}/generalBusiness/generalQueryBySQLSerialNumber`,
        type: "POST",
        data,
        success: function (Result) {
          if (Result.length > 0) {
            that.ExportData = Result;
            that.$nextTick(() => {
              let wb = XLSX.utils.table_to_book(
                document.querySelector("#ExportData")
              );
              var wbout = XLSX.write(wb, {
                bookType: "xlsx",
                bookSST: true,
                type: "array",
              });
              try {
                saveAs(
                  new Blob([wbout], {
                    type: "application/octet-stream",
                  }),
                  "采购订单表" + +new Date() + ".xlsx"
                );
              } catch (e) {
                if (typeof console !== "undefined") console.log(e, wbout);
              }
              that.$message({
                message: "已成功导出",
                type: "success",
              });
              return wbout;
            });
          } else {
            that.$message({
              message: "暂无可导出的数据",
              type: "warning",
            });
          }
        },
        complete: function (XMLHttpRequest) {
          that.loading = false;
          requestPretreatment(XMLHttpRequest);
        },
        dataType: "json",
      });
    },
  },
});
